﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using nyxwin.Data.Base;
using nyxwin.Data.Bookmarks;
using nyxwin.Data.Friends;
using nyxwin.Data.Mail;
using nyxwin.Common.Settings;
using nyxwin.Main.ViewModel;
using System.Windows.Data;
using nyxwin.Main.Base.View;
using nyxwin.Main.Base.Interfaces;
using System.Linq;
using nyxwin.Common.Resources;
using System.Collections.Generic;
using nyxwin.Common.Base.Utils;

namespace nyxwin.Main.View
{
    public partial class MainPage : PhoneApplicationPage, ISupportProgress, ISupportErrors
    {
        #region Fields

        private MainPageViewModel _model;
        private bool _left;

        #endregion

        #region Construction

        public MainPage()
        {
            InitializeComponent();

            this._left = false;
            this._model = new MainPageViewModel();
            this._model.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Model_PropertyChanged);
            this.DataContext = this._model;

            this.pivot.Items.Clear();

            foreach (var pivot in this._model.Pivots)
            {
                PivotItem pi = new PivotItem();

                Binding b = new Binding();
                b.Source = pivot.PivotViewModel;
                b.Path = new PropertyPath("Title");
                b.Mode = BindingMode.OneWay;

                pi.SetBinding(PivotItem.HeaderProperty, b);

                pi.Content = pivot;

                this.pivot.Items.Add(pi);
            }

            InitAppBarMenuItems();

            this.Unloaded += new RoutedEventHandler(MainPage_Unloaded);
        }

        void MainPage_Unloaded(object sender, RoutedEventArgs e)
        {
            this._model.Unload();
        }

        void Model_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "AppBarButtons")
            {
                InitAppBarButtons();
            }
            else if (e.PropertyName == "AppBarMenuItems")
            {
                InitAppBarMenuItems();
            }
        }
        #endregion

        #region OnNavigatedTo

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (this._left)
            {
                this._left = false;

                if (this._leftToExternal)
                {
                    this._leftToExternal = false;
                }
                else
                {
                    if (NavigationContext.QueryString.ContainsKey("pivot"))
                    {
                        var id = NavigationContext.QueryString["pivot"];
                        var viewModel = this._model.GetPivotItemViewFromId(id);

                        var pivotItem = pivot.Items[0];

                        foreach (var p in pivot.Items.OfType<PivotItem>())
                        {
                            if (p.Content == viewModel)
                            {
                                pivotItem = p;
                                break;
                            }
                        }

                        this._ignorePivotSelectionChanged = true;
                        pivot.SelectedItem = pivotItem;
                        this._ignorePivotSelectionChanged = false;

                        this._model.Enter(viewModel);
                    }
                    else if (this._lastSelect != null)
                        this._model.Enter(this._lastSelect);
                }
            }

            NavigationService.RemoveBackEntries();
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            this._left = true;

            if (e.Uri.IsAbsoluteUri && e.Uri.AbsoluteUri == "app://external/")
            {
                this._leftToExternal = true;
            }
            else
            {
                if (this._lastSelect != null)
                    this._model.Leave(this._lastSelect);
            }

            this.progresses.Clear();
        }

        #endregion

        #region Pivot_SelectionChanged
        PivotItemView _lastSelect = null;

        private void PivotSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_ignorePivotSelectionChanged)
                return;

            var pivotItem = pivot.SelectedItem as PivotItem;

            if (pivotItem == null)
                return;

            var pivotContentView = pivotItem.Content as PivotItemView;

            if (pivotContentView == null)
                return;

            if (_lastSelect != null)
                this._model.Leave(pivotContentView);

            this._model.Enter(pivotContentView);

            _lastSelect = pivotContentView;
        }

        #endregion

        #region AppBar
        private void InitAppBarMenuItems()
        {
            this.ApplicationBar.MenuItems.Clear();

            foreach (var item in this._model.AppBarMenuItems)
            {
                this.ApplicationBar.MenuItems.Add(item);
            }
        }

        private void InitAppBarButtons()
        {
            this.ApplicationBar.Buttons.Clear();

            foreach (var item in this._model.AppBarButtons)
            {
                this.ApplicationBar.Buttons.Add(item);
            }
        }
        #endregion

        #region ISupportProgress Members
        ProgressIndicator _progressIndicator = null;
        private bool _leftToExternal;
        private bool _ignorePivotSelectionChanged;

        private List<Tuple<Guid, string>> progresses = new List<Tuple<Guid, string>>();

        public void SetInDeterminate(Guid id, string text)
        {
            progresses.Add(new Tuple<Guid, string>(id, text));

            if (progresses.Count == 1)
            {
                if (_progressIndicator == null)
                {
                    _progressIndicator = new ProgressIndicator();
                    SystemTray.SetProgressIndicator(this, _progressIndicator);
                }

                _progressIndicator.IsIndeterminate = true;
                _progressIndicator.Text = text;
                _progressIndicator.IsVisible = true;
            }
        }

        public void UnSetInDeterminate(Guid id)
        {
            var removedProgress = progresses.FirstOrDefault(x => x.Item1 == id);

            if (removedProgress != null)
                progresses.Remove(removedProgress);

            if (_progressIndicator != null)
            {
                var first = progresses.FirstOrDefault();

                if (first == null)
                {
                    _progressIndicator.IsVisible = false;
                }
                else
                {
                    _progressIndicator.IsIndeterminate = true;
                    _progressIndicator.Text = first.Item2;
                    _progressIndicator.IsVisible = true;
                }
            }
        }

        #endregion

        #region ISupportErrors Members

        public void RaiseError(string message)
        {
            MessageBox.Show(message, LocalizationResource.Error, MessageBoxButton.OK);
        }

        #endregion
    }
}